<!-- 老人等级分布组件 -->
<template>
  <div class="elder-level-chart-container">
    <div
      id="elderLevelChart"
      ref="elderLevelChartContainer"
      class="chart-container" />
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted, watch } from "vue";
import * as echarts from "echarts/core";
import { TooltipComponent, LegendComponent } from "echarts/components";
import { PieChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";

// 注册ECharts组件
echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer]);

// 定义props
const props = defineProps({
  data: {
    type: Array,
    default: () => [
      { value: 100, name: "一级护理等级" },
      { value: 735, name: "二级护理等级" },
      { value: 580, name: "三级护理等级" },
      { value: 484, name: "四级护理等级" },
      { value: 300, name: "特级护理等级" },
    ],
  },
  title: {
    type: String,
    default: "护理等级分布",
  },
});

const elderLevelChartContainer = ref();
let elderLevelChart;

// 图表配置
const getChartOption = () => {
  return {
    color: ["#0052D9", "#00A870", "#FFB020", "#FF6B6B", "#8B5CF6"],
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        return `${params.name}<br/>${params.marker}数量: ${params.value}人<br/>占比: ${params.percent}%`;
      },
    },
    legend: {
      orient: "vertical",
      left: "left",
      textStyle: {
        color: "#666",
      },
    },
    series: [
      {
        name: props.title,
        type: "pie",
        radius: ["40%", "70%"],
        center: ["60%", "50%"],
        data: props.data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },

          labelLine: {
            show: true,
          },
        },
        label: {
          show: false,
          formatter: "{b}: {c}人",
        },
        labelLine: {
          show: false,
        },
      },
    ],
  };
};

// 初始化图表
const initChart = () => {
  if (elderLevelChartContainer.value) {
    elderLevelChart = echarts.init(elderLevelChartContainer.value);
    elderLevelChart.setOption(getChartOption());

    // 监听窗口大小变化
    window.addEventListener("resize", () => {
      elderLevelChart?.resize();
    });
  }
};

// 监听数据变化
watch(
  () => props.data,
  () => {
    if (elderLevelChart) {
      elderLevelChart.setOption(getChartOption());
    }
  },
  { deep: true }
);

onMounted(() => {
  initChart();
});

onUnmounted(() => {
  if (elderLevelChart) {
    elderLevelChart.dispose();
  }
  window.removeEventListener("resize", () => {
    elderLevelChart?.resize();
  });
});
</script>

<style lang="scss" scoped>
.elder-level-chart-container {
  margin-top: 30px;
  width: 100%;
  height: 100%;

  .chart-container {
    width: 100%;
    height: 240px;
    min-height: 240px;
  }
}
</style>
